# mahalFun :: function call sent to genoud to conduct genetic matching internal to the
#				genetic algorithm

mahalFun=function(w){
	options(warn=0)
	
	X=as.matrix(mMat) 
	chm=as.matrix(chol(var(X,na.rm=T)))
	n=nrow(X)
	k=ncol(X) 
	
	wM=matrix(0,k,k)
	diag(wM)=w
	SWS=t(chm)%*%wM%*%chm
	z=tr
	
	eps=.001		
	dMat=matrix(0,n,n)
	for(i in 1:n){
		if(i < n){
			dMat[i,(i+1):n]=mahalanobis(X[(i+1):n,],X[i,],cov=SWS,invert=T)/((z[i]-z[(i+1):n])^2+eps)
			dMat[(i+1):n,i]=dMat[i,(i+1):n]
		}
	}
   	
	aMat=dMat+1
	
	zMat=matrix(NA,length(tr),length(tr))
	for(i in 1:length(tr)){
		zMat[i,]=abs(tr[i]-tr)
	}
	zMat[which(zMat==0)]=.00001
	
	dMat=as.data.frame(as.matrix(aMat/zMat))
	outs=nbpGreedy(dMat=dMat)
		
	pvals=balFun(mMat=bMat,outs=outs,tr=tr)
	return(pvals)
}

